package com.meilai.project.aspect;

import com.meilai.project.constant.LoginTypeEnum;
import com.meilai.project.entity.system.OperateLog;
import com.meilai.project.service.system.OperateLogService;
import com.meilai.project.util.AOPUtil;
import com.meilai.project.util.IPUtils;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * aop打印web端操作日志
 */
@Aspect
@Component
@Log4j2
public class WebLogAspect {
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");

    @Autowired
    private OperateLogService operateLogService;

    @Pointcut("execution(public * com.meilai.project.controller.web..*.*(..))")//切入点描述 这个是controller包的切入点
    public void controllerLog(){}//签名，可以理解成这个切入点的一个名称

    @Before("controllerLog()") //在切入点的方法run之前要干的
    public void logBeforeController(JoinPoint joinPoint) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();

        Object userId = request.getAttribute("tokenUserId");
        Long operator_id = Long.valueOf(String.valueOf(userId!=null?userId:0L));

        if(!request.getRequestURI().startsWith("/api/web/message/get_own_unread_count")){
            // 不是请求消息中心未读数量，才打印日志
            LocalDateTime now = LocalDateTime.now();
            //log.info("【{} 前置打印log】web请求", now.format(formatter));

            OperateLog log = new OperateLog();
            log.setOperator_id(operator_id);
            log.setIp(IPUtils.getIPAddress(request));
            log.setType(LoginTypeEnum.WEB.getId());
            log.setUrl(request.getRequestURL().toString());
            log.setHttp_method(request.getMethod());
            log.setArgs(AOPUtil.getParams(joinPoint.getArgs()));
            log.setClass_method(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.setOperate_at(LocalDateTime.now());
            operateLogService.save(log);
        }
    }


}
